package cn.tsmchina.one.controller.m;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import cn.tsmchina.one.domain.order.Order;
import cn.tsmchina.one.domain.user.User;
import cn.tsmchina.one.service.order.OrderService;
import cn.tsmchina.one.service.user.CustomerService;
import cn.tsmchina.one.service.user.UserService;
import cn.tsmchina.one.util.C;
import cn.tsmchina.one.util.LoginUtil;
import cn.tsmchina.one.util.MD5Util;

/**
 * Description:
 * @author zhaoying 
 * @date 2013-10-4
 * @version 1.0
 * Copyright: Copyright (c) 2013 TSM,Inc
 */
@Controller
@RequestMapping("/user")
public class UserController {
	@Autowired
	private UserService userService;
	@Autowired
	private CustomerService customerService;
	@Autowired
	private OrderService orderService;

	@RequestMapping("/register")
	public String register(){
		return "m/register";
	}
	
	@RequestMapping("/login")
	public String login(){
		return "m/login";
	}
	
	/**
	 * 会员专区:进来显示我的订单
	 * 默认显示货到付款未送达
	 * 或者在线付款已付款的全部订单
	 * 如果没有，就显示最近5个订单
	 */
	@RequestMapping("/backend")
	public String backend(HttpServletRequest request){
		Long userId = (Long) request.getSession().getAttribute("userId");
		int page = 1;
		String curPage = request.getParameter("page");
		if(!StringUtils.isEmpty(curPage)){
			page = Integer.valueOf(curPage);
		}
		long cid = LoginUtil.getCustomerId(request, customerService);
		List<Order> olist = orderService.getUserOrders(userId, page, cid);
		request.setAttribute("orders", olist);
		
		int total = orderService.getUserOrders(userId, cid).size();
		if(total<=C.Paging.FRONT_PAGE_SIZE) {
			request.setAttribute("enablePage", false);
		} else {
			request.setAttribute("enablePage", true);
			if(page==1) {
				request.setAttribute("enableFirst", false);
			} else {
				request.setAttribute("enableFirst", true);
				request.setAttribute("prev", page-1);
			}
			
			int pageTotal = total % C.Paging.FRONT_PAGE_SIZE == 0 ? total / C.Paging.FRONT_PAGE_SIZE : total / C.Paging.FRONT_PAGE_SIZE + 1;
			if(page>=pageTotal) {
				request.setAttribute("enableLast", false);
			} else {
				request.setAttribute("enableLast", true);
				request.setAttribute("next", page+1);
			}
		}
		
		return "m/userBackend";
	}
	
	//会员专区：我的资料
	@RequestMapping("/userInfos")
	public String userInfos(){
		return "m/userInfos";
	}
	
	//会员专区：修改密码
	@RequestMapping("/userUpdatePass")
	public String userUpdatePass(){
		return "m/userUpdatePass";
	}
	
	@RequestMapping(value="/updatePass",method= RequestMethod.POST)
	@ResponseBody
	public Object updatePass(HttpServletRequest request,@RequestParam String curPass,
			@RequestParam String newPass,@RequestParam String confirmPass){
		Map<String, Object> data = new HashMap<>();
		User u = (User) request.getSession().getAttribute("user");
		if(null != u){
			if(MD5Util.validatePassword(u.getPassword(), curPass)){
				if(newPass.equals(confirmPass)){
					newPass = MD5Util.encodeByMD5(newPass);
					u.setPassword(newPass);
					if(userService.updateUserPass(u)){
						request.getSession().removeAttribute("user");
						request.getSession().removeAttribute("userId");
						request.getSession().removeAttribute("realName");
						request.getSession().removeAttribute("phone");
						request.getSession().removeAttribute("address");
						
						data.put("ok", C.Msg.OK);
						data.put("msg", "修改成功!");
					}else{
						data.put("ok", C.Msg.ERROR);
						data.put("msg", "修改失败，内部错误！");
					}
				}else{
					data.put("ok", C.Msg.ERROR);
					data.put("msg", "两次密码输入不一致！");
				}
			}
			else{
				data.put("ok", C.Msg.ERROR);
				data.put("msg", "原密码输入错误！");
			}
		}
		
		return data;
	}
	
	@RequestMapping(value="/register",method= RequestMethod.POST)
	@ResponseBody
	public Object register(@ModelAttribute User user,HttpServletRequest request){
		long cid = LoginUtil.getCustomerId(request, customerService);
		user.setPassword(MD5Util.encodeByMD5(user.getPassword()));
		Long uid = userService.addUser(user, cid);
		Map<String, Object> data = new HashMap<>();
		if(null != uid){
			if(uid >0){
				data.put("ok", C.Msg.OK);
				data.put("msg", "注册成功!");
			}else{
				data.put("ok", C.Msg.OK);
				data.put("msg", "你已经注册过！");
			}
		}
		else{
			data.put("ok", C.Msg.ERROR);
			data.put("msg", "注册失败!");
		}
		
		return data;
	}
	
	@RequestMapping(value="/loginValid",method= RequestMethod.POST)
	@ResponseBody
	public Object loginValid(@ModelAttribute User user,HttpServletRequest request,HttpServletResponse response){
		String phone = user.getPhone();
		String password = user.getPassword();
		
		Map<String, Object> data = new HashMap<>();
		if(!StringUtils.isEmpty(phone)&& !StringUtils.isEmpty(password)){
			password = MD5Util.encodeByMD5(password);
			long cid = LoginUtil.getCustomerId(request, customerService);
			User u = userService.loginValid(phone,password, cid);
			if(null != u){
				request.getSession().setAttribute("user", u);
				request.getSession().setAttribute("userId", u.getId());
				
				String realName = u.getRealName();
				if(StringUtils.isEmpty(realName)||"null".equals(realName)){
					realName = "";
				}
				request.getSession().setAttribute("realName",realName);
				request.getSession().setAttribute("phone", u.getPhone());
				request.getSession().setAttribute("address", u.getAddress());
				//默认存储7天
				String savetime="14";
				int saveTime=Integer.parseInt(savetime);//这里接受的表单值为天来计算的  
                int seconds=saveTime*24*60*60;  
				Cookie cookie = new Cookie("user",phone+"==="+password+"==="+cid+"==="+u.getId()); 
				cookie.setPath("/");
				cookie.setMaxAge(seconds); 
                response.addCookie(cookie);  
				data.put("ok", C.Msg.OK);
				data.put("msg", "登录成功!");
				return data;
			}
		}
		
		data.put("ok", C.Msg.ERROR);
		data.put("msg", "用户名或密码不正确!");
		return data;
	}
	
	@RequestMapping(value="/updateUser",method= RequestMethod.POST)
	@ResponseBody
	public Object updateUser(@ModelAttribute User user,HttpServletRequest request){
		Long userId = user.getId();
		//String password = user.getPassword();
		
		Map<String, Object> data = new HashMap<>();
		if(null != userId){
			User u = userService.updateUser(user);
			if(null != u){
				request.getSession().setAttribute("user", u);
				request.getSession().setAttribute("userId", u.getId());
				
				String realName = u.getRealName();
				if(StringUtils.isEmpty(realName)||"null".equals(realName)){
					realName = "";
				}
				request.getSession().setAttribute("realName",realName);
				
				request.getSession().setAttribute("phone", u.getPhone());
				request.getSession().setAttribute("address", u.getAddress());
				
				data.put("ok", C.Msg.OK);
				data.put("msg", "更新成功!");
				
				return data;
			}
		}
		
		data.put("ok", C.Msg.ERROR);
		data.put("msg", "更新失败！");
		return data;
	}
	
	@RequestMapping(value="/logout",method= RequestMethod.POST)
	@ResponseBody
	public Object logout(HttpServletRequest request,HttpServletResponse response){
		request.getSession().removeAttribute("user");
		request.getSession().removeAttribute("userId");
		request.getSession().removeAttribute("realName");
		request.getSession().removeAttribute("phone");
		request.getSession().removeAttribute("address");
		Cookie[] cook = request.getCookies();
		//删除cookie中保存的个人登录信息
		for(int i=0;i<cook.length;i++)
		{
			if(cook[i].getName()!=null && cook[i].getName().equals("user"))
			{
				cook[i].setMaxAge(0);
				cook[i].setPath("/");
				response.addCookie(cook[i]);
			}			
		}
		
		Cookie[] cook1 = request.getCookies();
		for(Cookie c:cook1)
		{
			System.out.println(c.getName());
			System.out.println(c.getValue());
		}
		Map<String, Object> data = new HashMap<>();
		data.put("ok", C.Msg.OK);
		data.put("msg", "退出成功!");
		return data;
	}		
}

